package cn.mumzone.pos.ui.fragment.bills;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.ruffian.library.widget.REditText;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.event.SearchBillEvent;
import cn.mumzone.pos.ui.widgets.PosTimePickerView;
import cn.mumzone.pos.ui.widgets.tablayout.MagicIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.ViewPagerHelper;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.CommonNavigator;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.abs.IPagerIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.abs.IPagerTitleView;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.indicators.LinePagerIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.titles.SimplePagerTitleView;
import cn.mumzone.pos.util.AppUtil;

/**
 * Created By Dlx
 * on 2019/6/22
 */
public class FRA_Bill extends BaseFragment {
    @BindView(R.id.et_search)
    REditText etSearchBill;
    @BindView(R.id.ll_input_bill)
    LinearLayout llInputBill;
    @BindView(R.id.indicator_bill)
    MagicIndicator indicatorBill;
    @BindView(R.id.viewpager_content)
    ViewPager billViewpager;
    @BindView(R.id.btn_search)
    Button searchRB;
    @BindView(R.id.bill_delete_iv)
    ImageView deleteIv;
    @BindView(R.id.fl_fragment_layout)
    FrameLayout frameLayout;

    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.ic_go_previous_day)
    ImageView ivGoPreviousDay;
    @BindView(R.id.ic_go_next_day)
    ImageView ivGoNextDay;

    private PosTimePickerView posTimePickerView;

    private Date currentDay;

    final String[] titles = {"商品", "服务"};
    private List<FRA_BillItem> fraList = new ArrayList<>();
    private FRA_BillItem fra_Goods;
    private FRA_BillItem fra_Service;
    private boolean isOnlyGoods = false;

    @Override
    protected void onUserVisible() {
        RxBus.getDefault().post(new SearchBillEvent(etSearchBill.getText().toString().trim()));
    }

    @Override
    protected void initEventAndData() {
        isOnlyGoods = AppUtil.isOnlyHasGoodsBusiness();
        initEditTextListener();
        if (isOnlyGoods) {
            fra_Goods = FRA_BillItem.newInstance(FRA_BillItem.GOODS);
            fraList.add(fra_Goods);

            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            transaction.add(R.id.fl_fragment_layout, fra_Goods);
            transaction.commitAllowingStateLoss();

        } else {
            fra_Service = FRA_BillItem.newInstance(FRA_BillItem.SERVICE);
            fra_Goods = FRA_BillItem.newInstance(FRA_BillItem.GOODS);

            fraList.add(fra_Goods);
            fraList.add(fra_Service);

            billViewpager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
                @Override
                public Fragment getItem(int position) {
                    return fraList.get(position);
                }

                @Override
                public int getCount() {
                    return fraList.size();
                }
            });
            initMagicIndicator();
        }

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        int nowYear = endDate.get(Calendar.YEAR);
        startDate.set(nowYear - 2, 0, 1);
        posTimePickerView = new PosTimePickerView.PosTimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                currentDay = date;
                setDateChanged(date);
            }
        }).isDialog(true).isCyclic(false).setOutSideCancelable(true)
                .setTitleText("选择时间")
                .setType(new boolean[]{true, true, true, false, false, false})
                .setDate(endDate)
                .setRangDate(startDate, endDate)
                .build();


        setDateChanged(endDate.getTime());
    }

    private void setDateChanged(Date currentDay) {
        tvDay.setText(String.format("%s %s", AppDateUtil.getDateToString(currentDay.getTime(), AppDateUtil.YYYY_MM_DD1),
                AppDateUtil.getWeekOfDate(currentDay.getTime())));
        if (AppDateUtil.isSameDay(currentDay, new Date())) {
            ivGoNextDay.setVisibility(View.INVISIBLE);
        } else {
            ivGoNextDay.setVisibility(View.VISIBLE);
        }

        if (null != this.currentDay) {
            fra_Goods.setDateTime(currentDay.getTime());
            if (!isOnlyGoods) {
                fra_Service.setDateTime(currentDay.getTime());
            }
        }
        this.currentDay = currentDay;

    }

    @Override
    protected int getLayout() {
        return R.layout.fra_bill;
    }


    private void initMagicIndicator() {

        indicatorBill.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return titles.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(Color.GRAY);
                simplePagerTitleView.setSelectedColor(Color.BLACK);
                simplePagerTitleView.setText(titles[index]);
                simplePagerTitleView.setTextSize(getSpValue(18));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        billViewpager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setColors(Color.BLACK);
                return linePagerIndicator;
            }

        });
        indicatorBill.setNavigator(commonNavigator);
        ViewPagerHelper.bind(indicatorBill, billViewpager);
    }

    private void initEditTextListener() {
        etSearchBill.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        etSearchBill.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    searchRB.setEnabled(true);
                    setViewVisibility(deleteIv, true);
                } else if (s.toString().length() == 0) {
                    searchRB.setEnabled(false);
                    RxBus.getDefault().post(new SearchBillEvent(etSearchBill.getText().toString().trim()));
                }
            }
        });
        etSearchBill.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    EditTextUtil.hideSoftInput(mContext, v);

                    RxBus.getDefault().post(new SearchBillEvent(etSearchBill.getText().toString().trim()));
                }
                return false;
            }
        });
    }

    private float getSpValue(int spValue) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, getResources().getDisplayMetrics());
    }


    @OnClick({R.id.bill_delete_iv, R.id.btn_search, R.id.tv_day, R.id.ic_go_previous_day, R.id.ic_go_next_day})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bill_delete_iv:
                setViewVisibility(deleteIv, false);
                etSearchBill.setText("");
                RxBus.getDefault().post(new SearchBillEvent(etSearchBill.getText().toString().trim()));
                break;
            case R.id.btn_search:

                if (!NetUtil.isNetworkAvailable(mContext)) {
                    PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                    return;
                }

                RxBus.getDefault().post(new SearchBillEvent(etSearchBill.getText().toString().trim()));

                break;
            case R.id.ic_go_previous_day:
                if(getCurrentFragment().isRefreshing()){
                    return;
                }
                currentDay = new Date(AppDateUtil.getPreviousDay(currentDay.getTime()));
                setDateChanged(currentDay);
                break;
            case R.id.ic_go_next_day:
                if(getCurrentFragment().isRefreshing()){
                    return;
                }
                currentDay = new Date(AppDateUtil.getNextDay(currentDay.getTime()));
                setDateChanged(currentDay);
                break;
            case R.id.tv_day:
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDay);
                posTimePickerView.setDate(calendar);
                posTimePickerView.show();
                break;
        }
    }


    public FRA_BillItem getCurrentFragment() {
        return fraList.get(billViewpager.getCurrentItem());
    }

}
